package handler

import (
	"net/http"
	v1 "server_go/api/v1"
	"server_go/internal/service"
	"strconv"

	"github.com/gin-gonic/gin"
)

type TagHandler struct {
	*Handler
	tagService service.TagService
}

func NewTagHandler(
	handler *Handler,
	tagService service.TagService,
) *TagHandler {
	return &TagHandler{
		Handler:    handler,
		tagService: tagService,
	}
}

func (h *TagHandler) GetTags(ctx *gin.Context) {
	tags, err := h.tagService.GetTags(ctx)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, tags)
}
func (h *TagHandler) CreateTag(ctx *gin.Context) {
	userType := GetUserTypeFromCtx(ctx)
	if userType != 1 {
		v1.HandleError(ctx, http.StatusUnauthorized, v1.ErrUnauthorized, nil)
		return
	}
	req := new(v1.CreateTagRequest)
	if err := ctx.ShouldBindJSON(req); err != nil {
		v1.HandleError(ctx, http.StatusBadRequest, err, nil)
		return
	}
	err := h.tagService.CreateTag(ctx, *req)
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}
func (h *TagHandler) DeleteTag(ctx *gin.Context) {
	userType := GetUserTypeFromCtx(ctx)
	if userType != 1 {
		v1.HandleError(ctx, http.StatusUnauthorized, v1.ErrUnauthorized, nil)
		return
	}
	tagId := ctx.Param("tagId")
	if tagId == "" {
		v1.HandleError(ctx, http.StatusBadRequest, nil, gin.H{"error": "tagId不存在"})
	}
	TagId, err := strconv.Atoi(tagId)
	err = h.tagService.DeleteTag(ctx, uint(TagId))
	if err != nil {
		v1.HandleError(ctx, http.StatusInternalServerError, err, nil)
		return
	}
	v1.HandleSuccess(ctx, nil)
}
